package com.springcloud.gateway.config;

import com.springcloud.gateway.exception.GlobalExceptionHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.List;

/**
 * 网关配置类
 * 配置网关的各类组件，包括异常处理、过滤器等
 */
@Configuration
public class GatewayConfig {

    /**
     * 注册全局异常处理器
     * @param viewResolvers 视图解析器列表
     * @param serverCodecConfigurer 服务编解码器配置器
     * @return 错误异常处理器
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = ConditionalOnMissingBean.SearchStrategy.CURRENT)
    public ErrorWebExceptionHandler errorWebExceptionHandler(List<ViewResolver> viewResolvers, 
                                                           ServerCodecConfigurer serverCodecConfigurer) {
        GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler();
        exceptionHandler.setViewResolvers(viewResolvers);
        exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}